package gui;


import client.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.StringWriter;
//import test.*;

/**
 *
 * @author  tomek
 */
public class RegistrationGui extends JFrame implements ActionListener, WindowListener {
    
    private Registration myRegistration;
    
    static final String titledBorderString = "Rejestracja";
    //texts for buttons on bottom
    static final String REGISTER = "Zarejestruj";
    static final String CANCEL = "Anuluj";
    
    static final byte MAX_FIELDS = 6;
    
    private String stringList[] = {"Login", "Adres e-mail", "Imie", "Nazwisko", "Miejscowosc", "Rok urodzenia", "Hasło", "Powtórz hasło"};
    private JPanel mainPanel, bottomPanel;
    private JLabel[] labels;
    private JTextField[] textFields;
    private JPasswordField passwd;
    private JPasswordField passwd_confirm;

    private JButton jButton1;
    private JButton jButton2;    
    
    public RegistrationGui(Registration r) {
        super(titledBorderString);
        myRegistration = r;
//        this.setSize(200, 200);
        initComponents();
    }
    
    private void initComponents() {
        
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(UsersListGui.createIcon(UsersListGui.Menu.REGISTER.imgURL()).getImage());
        addWindowListener(this);
        //creates JPanel for labels and text field
        mainPanel = new JPanel();
        mainPanel.setLayout(new java.awt.GridLayout(0,2,0,10));
        
        mainPanel.setBorder(new javax.swing.border.TitledBorder(titledBorderString));
        
        add(mainPanel);
        
        //2 additional labels for password and confirmation
        labels = new JLabel[MAX_FIELDS+2];
        textFields = new JTextField[MAX_FIELDS];
        
        for (byte i = 0; i < MAX_FIELDS; i++) {
            labels[i] = new JLabel(stringList[i]);
            textFields[i] = new JTextField(20);
            mainPanel.add(labels[i]);
            mainPanel.add(textFields[i]);
        }
        
        labels[6] = new JLabel(stringList[6]);
        passwd = new JPasswordField();
        mainPanel.add(labels[6]);
        mainPanel.add(passwd);
        
        labels[7] = new JLabel(stringList[7]);
        passwd_confirm = new JPasswordField();
        mainPanel.add(labels[7]);
        mainPanel.add(passwd_confirm);

        
        bottomPanel = new JPanel();
        bottomPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 10, 10));
        jButton1 = new JButton();
        jButton2 = new JButton();
        bottomPanel.add(jButton1);
        bottomPanel.add(jButton2);

        mainPanel.add(new JLabel(""));
        mainPanel.add(bottomPanel);
        
        jButton1.setText(CANCEL);
        jButton1.setActionCommand(CANCEL);
        jButton2.setText(REGISTER);      
        jButton2.setActionCommand(REGISTER);
        
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
  
    }

    public void showGui() {
        pack();
        super.setVisible(true);
    }
    
    public void showErrorDialog() {
        JOptionPane.showMessageDialog(new JFrame(), "Podczas proby nawiazania polaczenia wystapil blad.\nSprobuj ponownie.", "Blad polaczenia", JOptionPane.ERROR_MESSAGE);
    }
    
    public void showConfirmationDialogAndDispose() {
        JOptionPane.showMessageDialog(new JFrame(), "Rejestracja powiodla sie.", "Uzytkownik zarejestrowany", JOptionPane.INFORMATION_MESSAGE);
        dispose();
    }
            
    
    //ActionListener method
    public void actionPerformed(ActionEvent evt) {
        if (REGISTER.equals(evt.getActionCommand())) {
            
            String login;
            String email;
            String firstName;
            String lastName;
            String city;
            String born = null;
            char[] passwd_hash;
            char[] passwd_conf;
            String hash = null;
            
            Pattern p;
            Matcher m;
            boolean b;
            boolean error = false;
            
            StringWriter warning = new StringWriter();
                        
            warning.append("Nastapil blad przy wpisywaniu:\n");
            
            login = textFields[0].getText();
            p = Pattern.compile("[a-z1-9\\.\\_\\-]{3,}");
            m = p.matcher(login);
            b = m.matches();
            if (!b) {
                error = true;
                warning.append("loginu\n");
            //    System.out.println("Zly login");
            }
            
            
            email = textFields[1].getText();
            p = Pattern.compile("[a-z1-9\\.\\_\\-]+@[a-z1-9\\.\\-]+\\.[a-z]{2,3}");
            m = p.matcher(email);
            b = m.matches();
            if (!b) {
                error = true;
                warning.append("adresu e-mail\n");
            }
            
            firstName = textFields[2].getText();
            p = Pattern.compile("[a-zA-Z]+");
            m = p.matcher(firstName);
            b = m.matches();
            if (!b) {
                error = true;
                warning.append("imienia\n");
            }
  
            lastName = textFields[3].getText();
            p = Pattern.compile("[a-zA-Z]+");
            m = p.matcher(lastName);
            b = m.matches();
            if (!b) {
                error = true;
                warning.append("nazwiska\n");
            }
  
            city = textFields[4].getText();
            p = Pattern.compile("[a-zA-Z]+");
            m = p.matcher(city);
            b = m.matches();
            if (!b) {
                error = true;
                warning.append("miasta\n");
            }
            
            try {
                born = textFields[5].getText();
                p = Pattern.compile("[1-9]{4}");
                m = p.matcher(textFields[5].getText());
                b = m.matches();
                if (!b) {
                    error = true;
                    warning.append("roku urodzenia\n");
                }
            }
            catch (NumberFormatException e) {
                error = true;
                warning.append("roku urodzenia\n");
            }
    
            passwd_hash = passwd.getPassword();
            passwd_conf = passwd_confirm.getPassword();
            if (passwd_hash.length < 6) {
                error = true;
                warning.append("hasla - zbyt krotkie\n");
            }
            else if (!java.util.Arrays.equals(passwd_hash, passwd_conf)) {
                error = true;
                warning.append("hasla - nie zgadzaja sie\n");
            }
            
            if(error) {
                JOptionPane.showMessageDialog(new JFrame(), warning, "Blad", JOptionPane.ERROR_MESSAGE);
//                System.out.println(warning);
            }
            else {
                //TODO sprawdzanie czy podany login jest wolny

                //haszowanie hasla
                try {
                    hash = CryptoUtils.byteArrayToHexString(CryptoUtils.computeHash(String.copyValueOf(passwd_conf)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("\nthe computed hash (hex string) : " + hash);

                //rejestracja
                myRegistration.sendRegistrationRequest(login, hash, email, firstName, lastName, born, city);

            }
        }
        else {
            if (JOptionPane.showConfirmDialog(new JFrame(), "Czy na pewno chcesz wyjść z rejestracji?\nUtracisz wszystkie wpisane dane.\n", "Rejestracja - wyjscie", JOptionPane.YES_NO_OPTION) == 0) {
                dispose();
            }  
        }
    }
    
    //WindowListener methods
    public void windowActivated(WindowEvent e) {}
    public void	windowClosed(WindowEvent e) {}
    public void	windowClosing(WindowEvent e) {
        if(JOptionPane.showConfirmDialog(new JFrame(), "Czy na pewno chcesz wyjść z rejestracji?\nUtracisz wszystkie wpisane dane.\n", "Rejestracja", JOptionPane.YES_NO_OPTION) == 0) {
            dispose();
        }
    }
    public void	windowDeactivated(WindowEvent e) {}
    public void	windowDeiconified(WindowEvent e) {}
    public void	windowIconified(WindowEvent e) {}
    public void	windowOpened(WindowEvent e) {}
    
}
